﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Web;
using System.Text;
using System.Collections.Generic;
using Microsoft.SharePoint.WebControls;

namespace Poll.PollWebPart
{
    public partial class PollWebPartUserControl : UserControl
    {

        public string LastQuestion { get; set; }
        public int MaxColumns = 70;
        public string ListPath { get; set; }
        public string ForeColor { get; set; }
        public string BackColor { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.lblSource.Text = string.Empty;
            this.btnSubmitQuestion.Visible = false;
            this.btnCreateList.Visible = false;

            SPSite site = SPContext.Current.Site;
            SPWeb web = site.RootWeb;

            this.lblResult.Text = "Problem: No questions were in the list to ask.  You must add questions.  <a href=\""+ web.Url + "/Lists/" + ListPath + "\">Click here to be redirected to that list.</a>";

            if (ListPath == null)
            {
                this.lblResult.Text = "Problem: This must be the first time you have used this web part.  You must now configure this web part.";
                return;
            }

            if (ListPath.Length > 0 && !ListPathExists())
            {
                this.lblResult.Text = "Problem: You have now configured your list settings to " + ListPath+ ", however the list is not created...  Use the button below to create the list.";
                this.btnCreateList.Visible = true;
                this.btnCreateList.Text = "Create List At \"/Lists/" + ListPath + "\".";
                return;
            }

            try
            {
                if (!IsPostBack)
                {

                    LastQuestion = GetLastQuestionName().Replace(" ", "").Trim();

                    // Checks to see if question was asked based on a cookie...
                    bool isCompleted = CheckIfQuestionCompleted();

                    if (isCompleted)
                    {
                        // Renders the results of the question
                        ShowResults();
                    }
                    else
                    {
                        this.btnSubmitQuestion.Visible = true;
                        // New to this question...
                        ShowQuestion();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private bool ListPathExists()
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = site.RootWeb;

            foreach (SPList list in web.Lists)
            {
                if (list.Title == ListPath)
                {
                    return true;
                }
            }

            return false;
        }

        private void ShowQuestion()
        {
            try
            {
                PollResult pollResult = GetQuestionData();

                StringBuilder question = new StringBuilder();

                question.Append("<strong>" + pollResult.Question + "</strong><br /><br />");

                if (pollResult.Description != null)
                {
                    if (pollResult.Description.Length > 0)
                    {
                        question.Append(pollResult.Description + "<br /><br />");
                    }
                }

                this.lblResult.Text = question.ToString();
                                
                this.rdoShowQuestions.DataSource = pollResult.Results;
                this.rdoShowQuestions.DataTextField = "Option";
                this.rdoShowQuestions.DataValueField = "ID";
                this.rdoShowQuestions.DataBind();

                if (pollResult.Source != null)
                {
                    if (pollResult.Source.Length > 0)
                    {
                        this.lblSource.Text = "<br />Source: <strong><a href=\"" + pollResult.SourceURL + "\" target=\"_blank\">" + pollResult.Source + "</a></strong><br /><br />";
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private bool CheckIfQuestionCompleted()
        {
            try
            {
                if (HttpContext.Current.Request.Cookies[LastQuestion] == null)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Can't finish this process..");
            }
        }

        private void WriteCookie()
        {
            try
            {
                HttpCookie cookie = new HttpCookie(GetLastQuestionName().Trim().Replace(" ",""));
                cookie.Value = "true";
                cookie.Expires = DateTime.Now.AddDays(14);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch (Exception ex)
            {
            }
        }

        public string GetLastQuestionName()
        {
            try
            {
                string response = string.Empty;
                SPSite site = SPContext.Current.Site;
                
                    SPWeb web = site.RootWeb;
                    SPList list = web.Lists[this.ListPath];

                    response = list.Items[list.ItemCount - 1]["Title"].ToString();

                
                return response;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private void ShowResults()
        {
            try
            {
                this.btnSubmitQuestion.Visible = false;
                this.rdoShowQuestions.Visible = false;

                PollResult pollResult = GetQuestionData();

                this.lblResult.Text = BuildResultTable(pollResult);
            }
            catch (Exception ex)
            {
            }
        }

        private PollResult GetQuestionData()
        {
            try
            {
                PollResult pollResult = new PollResult();

                SPSite site = SPContext.Current.Site;
                
                    SPWeb web = site.RootWeb;

                    SPList list = web.Lists[this.ListPath];

                    pollResult.Question = list.Items[list.ItemCount - 1]["Title"].ToString();

                    pollResult.Description = list.Items[list.ItemCount - 1]["Description"].ToString();

                    pollResult.Source = list.Items[list.ItemCount - 1]["Source"].ToString();

                    pollResult.SourceURL = list.Items[list.ItemCount - 1]["SourceURL"].ToString();

                    // Gets all of the options...
                    for (int i = 1; i < MaxColumns + 1; i++)
                    {
                        try
                        {
                            pollResult.Results.Add(new PollResultItem()
                            {
                                ID = i,
                                Option = list.Items[list.ItemCount - 1]["Option" + i.ToString().Trim()].ToString(),
                                TotalResults = int.Parse(list.Items[list.ItemCount - 1]["Response" + i.ToString().Trim()].ToString())
                            });
                        }
                        catch { this.MaxColumns = i; }
                    }

                    // Populates all of the totals to the root item
                    foreach (PollResultItem item in pollResult.Results)
                    {
                        pollResult.TotalResults += item.TotalResults;
                    }

                    // Populates the percentage for all the items
                    foreach (PollResultItem item in pollResult.Results)
                    {
                        try
                        {
                            item.Percent = (int)((item.TotalResults * 100) / pollResult.TotalResults);
                        }
                        catch
                        {
                            item.Percent = 0;
                        }
                    }
                return pollResult;
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private string BuildResultTable(PollResult pollResult)
        {
            try
            {
                pollResult.Results.Sort(delegate(PollResultItem p1, PollResultItem p2)
                    { return p2.TotalResults.CompareTo(p1.TotalResults); });

                StringBuilder response = new StringBuilder();

                response.Append("<strong>" + pollResult.Question + "</strong><br />");
                if (pollResult.Description != null)
                {
                    if (pollResult.Description.Length > 0)
                    {
                        response.Append("<br />" + pollResult.Description + "<br />");
                    }
                }

                response.Append("<br />Total Results: <strong>" + pollResult.TotalResults.ToString().Trim() + "</strong><br /><br />");

                // Starts the new table...
                response.Append("<table cellpadding=0 cellspacing=0 style\"margin:0px;width:100%;border-width: 0px;border-spacing: 0px;border-style: none;border-color: gray;border-collapse: collapse;background-color: white;\">\r\n");

                foreach (PollResultItem item in pollResult.Results)
                {
                    if (item.TotalResults > 0)
                    {

                        // Option Text
                        response.Append("<tr>\r\n<td style=\"margin:0px;border-width: 0px;padding: 0px;border-style: inset;-moz-border-radius: ;\">" + item.Option + " " +item.TotalResults.ToString()  +" "+ GetVoteText(item.TotalResults,"vote","votes") +" (" + item.Percent.ToString() + "%)</td></tr>\r\n");

                        // Builds sub table...
                        response.Append("<tr>\r\n<td style=\"margin:0px;width:100%\"><table cellpadding=0 cellspacing=0 style=\"margin:0px;height:100%;border-width: 0px;width:100%;height:100%;\">\r\n");

                        // Result Positive
                        response.Append("<td style=\"margin:0px;height:100%;width:" + item.Percent.ToString() + "%;background-color:" + this.ForeColor.ToString() + ";\">&nbsp;</td>\r\n");

                        // Result Negitave
                        response.Append("<td style=\"margin:0px;height:100%;width:" + (100 - item.Percent).ToString() + "%;background-color:" + this.BackColor.ToString() + ";\"></td>\r\n");

                        // Closes the sub table
                        response.Append("</td></table></tr>\r\n");
                        
                        // Add an empty line...
                        response.Append("<tr>\r\n<td style=\"margin:0px;border-width: 0px;padding: 0px;border-style: inset;-moz-border-radius: ;\">&nbsp;</td></tr>\r\n");
                    }
                }

                // Closes the table...
                response.Append("</table>\r\n");
                if (pollResult.Source != null)
                {
                    if (pollResult.Source.Length > 0)
                    {
                        response.Append("Source: <strong><a href=\"" + pollResult.SourceURL + "\" target=\"_blank\">" + pollResult.Source + "</a></strong>");
                    }
                }
                return response.ToString();
            }
            catch (Exception ex)
            {
                return null;
            }
        }

        private string GetVoteText(int total, string singular, string pleural)
        {
            if (total == 1)
            {
                return singular;
            }
            else
            {
                return pleural;
            }
        }

        protected void btnSubmitQuestion_Click(object sender, EventArgs e)
        {
            try
            {
                PollResult pollResult = GetQuestionData();

                int selectedOption = int.Parse(this.rdoShowQuestions.SelectedItem.Value);

                SPSite site = SPContext.Current.Site;
                SPWeb web = site.RootWeb;

                SPList list = web.Lists[this.ListPath];

                SPListItemCollection items = list.GetItems(new SPQuery()
                {
                    Query = "<Where>"
                            + "   <Eq>"
                            + "      <FieldRef Name='Title' />"
                            + "      <Value Type='Text'>" + pollResult.Question + "</Value>"
                            + "   </Eq>"
                            + "</Where>"
                });

                foreach (SPListItem item in items)
                {
                    int pollItemIndex = -1;
                    foreach (PollResultItem pollItem in pollResult.Results)
                    {
                        pollItemIndex++;
                        if (pollItem.ID == selectedOption)
                        {
                            item["Response" + selectedOption] = pollResult.Results[pollItemIndex].TotalResults + 1;
                            item.Update();
                        }
                    }
                }
                // Writes new cookie...
                WriteCookie();
                ShowResults();
            }
            catch (Exception ex)
            {

            }
        }

        protected void btnCreateList_Click(object sender, EventArgs e)
        {
            SPSite site = SPContext.Current.Site;
            SPWeb web = site.RootWeb;

            web.AllowUnsafeUpdates = true;
            web.Lists.Add(this.ListPath, "Created by the PollWebPart", SPListTemplateType.GenericList);
            SPList pollsList = web.Lists[this.ListPath];
            SPView view = pollsList.Views["All Items"];
            SPViewFieldCollection viewFields = view.ViewFields;

            SPField field = pollsList.Fields["Title"];
            field.Title = "Title";
            field.Update();

            string fieldID = string.Empty;

            fieldID = pollsList.Fields.Add("Description", SPFieldType.Note, false);
            field = (SPField)pollsList.Fields.GetField(fieldID);
            viewFields.Add(field);
            view.Update();

            fieldID = pollsList.Fields.Add("Source", SPFieldType.Text, false);
            field = (SPField)pollsList.Fields.GetField(fieldID);
            viewFields.Add(field);
            view.Update();

            fieldID = pollsList.Fields.Add("SourceURL", SPFieldType.Text, false);
            field = (SPField)pollsList.Fields.GetField(fieldID);
            viewFields.Add(field);
            view.Update();

            for (int i = 1; i < MaxColumns + 1; i++)
            {
                fieldID = pollsList.Fields.Add("Option" + i.ToString().Trim(), SPFieldType.Note, false);
                field = (SPField)pollsList.Fields.GetField(fieldID);
                viewFields.Add(field);
                view.Update();

                fieldID = pollsList.Fields.Add("Response" + i.ToString().Trim(), SPFieldType.Number, true);
                field = (SPField)pollsList.Fields.GetField(fieldID);
                viewFields.Add(field);
                view.Update();
                field.DefaultValue = "0";
                field.Update();
            }

            Page.Response.Redirect(web.Url + "/Lists/" + this.ListPath);
        }
    }
}
